package com.example.zzb.mycalculater;

import java.util.Stack;
import java.text.DecimalFormat;

/**
 * Created by Zzb on 2017/4/19.
 */

public class Calculater {

    public String my_expression(String expression) {
        try {
            String[] s1 = expression.split("[+|-]"); // 根据加减运算符分割字符串
            for (int i = 0; i < s1.length; i++) {
                String[] nums1 = s1[i].split("[*|/]");
                String depoint = s1[i].replaceAll("\\.", "");

                char[] ops1 = depoint.replaceAll("\\d+", "").toCharArray();
                String num = md(nums1, ops1);
                s1[i] = num;
            }
            // 计算加减运算
            String depoint2 = expression.replaceAll("\\.|\\*|\\/", "");
            char[] ops2 = depoint2.replaceAll("\\d+", "").toCharArray();
            String value = md(s1, ops2);
            return value;
        } catch (Exception e) {
            return "error!";
        }

    }

    private static String md(String[] nums, char[] ops) {
        double num = Double.valueOf(nums[0]).doubleValue();
        for (int i = 1; i < nums.length; i++) {
            switch (ops[i - 1]) {
                case '*':
                    num = num * Double.valueOf(nums[i]).doubleValue();
                    break;
                case '/':
                    num = num / Double.valueOf(nums[i]).doubleValue();
                    break;
                case '+':
                    num = num + Double.valueOf(nums[i]).doubleValue();
                    break;
                case '-':
                    num = num - Double.valueOf(nums[i]).doubleValue();
                    break;
            }
        }
        return Double.toString(num);
    }
}
